package force;

import backbone.IForceable;
import java.awt.Point;
import java.awt.geom.Point2D;
import main.Simulation;

/**
 * Class specifies centerofmass force.
 * @author Paul
 * @author Lance
 *
 */
public class CenterOfMassForce extends InversePowerForce {
    
    private static final String NAME = "CoM";
    /**
     * @param scaleFactor factor for scaling this force
     * @param magnitude magnitude of the force
     */
    public CenterOfMassForce(final double scaleFactor, final double magnitude) {
        super(scaleFactor, magnitude, NAME);
    }

    /**
     * @return center of mass of simulation
     */
    private Point2D computeCenterOfMass() {
        double x = 0;
        double y = 0;
        double totalMass = 0;
        for (IForceable forceable : getForceables()) {
            x += forceable.getPosition().getX() * forceable.getMass();
            y += forceable.getPosition().getY() * forceable.getMass();
            totalMass += forceable.getMass();
        }
        Point2D point = new Point();
        point.setLocation(x / totalMass , y / totalMass);
        return point;
    }

    @Override
    public final void update(final Simulation canvas, final double dt) {
        Point2D pt = computeCenterOfMass();
        for (IForceable forceable : getForceables()) {
            Force f = computeInverseForce(pt, forceable.getPosition());
            forceable.applyForce(f);
        }
    }

}
